package handler

import (
	"2301house/api/request"
	"2301house/api/resp"
	"2301house/internal/dao"
	"2301house/internal/model"
	"github.com/gin-gonic/gin"
	"log"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrder
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "参数错误", err.Error())
		return
	}
	var order model.Order
	dao.GetOneByFields(&model.Order{
		UserId:  c.GetUint("userId"),
		HouseId: req.HouseId,
	}, &order)
	if order.Id != 0 {
		resp.Error(c, 10000, "当前订单已存在", nil)
		return
	}
	result := dao.Create(&model.Order{
		UserId:  c.GetUint("userId"),
		HouseId: req.HouseId,
		Price:   req.Price,
		PayUrl:  req.PayUrl,
	})
	if !result {
		resp.Error(c, 10000, "添加购房订单失败", nil)
		return
	}
	resp.Success(c, "添加购房订单成功", nil)

}

func UploadPayUrl(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		resp.Error(c, 10000, "参数错误", err.Error())
		return
	}
	log.Println(file.Filename)
	dst := "D:\\gowork\\src2\\2301house\\static\\upoload\\" + file.Filename
	err = c.SaveUploadedFile(file, dst)
	if err != nil {
		resp.Error(c, 10000, "上传失败", nil)
		return
	}
	resp.Success(c, "上传成功", "http://127.0.0.1:8080/upload/"+file.Filename)

}

func UpdateOrderType(c *gin.Context) {
	var req request.UpdateOrderType
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "参数错误", err.Error())
		return
	}
	userId := c.GetUint("userId")
	if !(userId == 2 || userId == 3) {
		resp.Error(c, 10000, "没有权限修改", nil)
	}
	var order model.Order
	dao.GetOneByFields(&model.Order{
		Id: req.Id,
	}, &order)
	if order.Id != 0 {
		resp.Error(c, 10000, "当前订单不存在，无法修改", nil)
		return
	}
	result := dao.Update(&model.Order{
		Id:    req.Id,
		OType: 1, //当房屋状态为1时，房源待审核
	})
	if !result {
		resp.Error(c, 10000, "修改订单状态失败", nil)
		return
	}
	resp.Success(c, "修改订单状态成功", nil)

}
